package com.example.game_app.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.game_app.R;
import com.example.game_app.util.Request;
import com.example.game_app.util.UserContext;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

public class StrategyListAdapter extends ArrayAdapter<Map<String, String>> {
    private Context context;
    private List<Map<String, String>> strategyList;
    private OnItemClickListener itemClickListener;

    private Handler mHandler = new Handler(Looper.getMainLooper());

    List<String> strategyIdList = new ArrayList<>();

    public StrategyListAdapter(@NonNull Context context, List<Map<String, String>> strategyList, OnItemClickListener itemClickListener) {
        super(context, R.layout.game_strategy_view, strategyList);
        this.context = context;
        this.strategyList = strategyList;
        this.itemClickListener = itemClickListener;
    }

    /**
     * 在ListView中显示每个项目的视图。这是Adapter的getView方法的实现。
     *
     * @param position    当前项目的索引位置
     * @param convertView 一个可重用的视图，如果可用，则可以避免创建新的视图
     * @param parent      视图的父容器
     * @return 返回用于显示列表项的视图
     */
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        ViewHolder viewHolder;
        // 检查convertView是否为空，如果为空，则需要创建一个新的视图
        if (convertView == null) {
            // 使用LayoutInflater从XML布局文件中创建一个新的视图
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.game_strategy_item, parent, false);
            viewHolder = new ViewHolder();
            // 初始化ViewHolder中的各个视图组件
            viewHolder.strategy_item_tag = convertView.findViewById(R.id.strategy_item_tag);
            viewHolder.strategy_item_title = convertView.findViewById(R.id.strategy_item_title);
            viewHolder.strategy_item_content = convertView.findViewById(R.id.strategy_item_content);
            viewHolder.if_user_strategy = convertView.findViewById(R.id.if_user_strategy);
            // 将ViewHolder对象与convertView绑定，以便后续重用
            convertView.setTag(viewHolder);
        } else {
            // 如果convertView不为空，则从其标签中获取ViewHolder对象
            viewHolder = (ViewHolder) convertView.getTag();
        }
        // 获取当前位置的策略数据
        Map<String, String> strategies = getItem(position);
        // 如果数据不为空，则将数据显示在视图上
        if (strategies != null) {
            viewHolder.strategy_item_tag.setText(strategies.get("gameName"));
            viewHolder.strategy_item_title.setText(strategies.get("strategyName"));
            viewHolder.strategy_item_content.setText(strategies.get("strategyContent"));
            // 判断是否 需要设置 [我的] 标签
            getUserStrategyIds(UserContext.getUser(context));
            String strategyId = strategies.get("strategyId");
            if (strategyIdList.contains(strategyId)) {
                viewHolder.if_user_strategy.setText("<删除攻略>");
                viewHolder.if_user_strategy.setOnClickListener(v -> {
                    // 创建弹出框
                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
                    TextView messageView = new TextView(context);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        messageView.setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Body1);
                        messageView.setGravity(Gravity.CENTER);
                        messageView.setTextSize(20);
                    }
                    String message = "是否删除您的攻略？？？";
                    messageView.setText(message);
                    alertDialogBuilder.setView(messageView);
                    alertDialogBuilder.setPositiveButton("确定", (dialog, which) -> {
                                new Thread(() -> {
                                    Request.post("/strategies/delete", "strategyId=" + strategyId);
                                }).start();
                                mHandler.post(() -> {
                                    strategyList.remove(position);
                                    notifyDataSetChanged();
                                    Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
                                });
                            })
                            .setNegativeButton("取消", null)
                            .create()
                            .show();
                });
            } else {
                viewHolder.if_user_strategy.setText("");
            }
        }
        // 为convertView设置一个标签，记录其位置，以便点击时可以获取到
        convertView.setTag(R.id.strategyLists, position);
        // 设置convertView的点击事件监听器
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 从视图中正确获取绑定的position
                int position1 = (Integer) v.getTag(R.id.strategyLists);
                Map<String, String> strategy = getItem(position1);
                if (itemClickListener != null) {
                    itemClickListener.onItemClick(strategy);
                }
            }
        });
        // 返回用于显示的视图
        return convertView;
    }

    /**
     * 根据 当前用户id 查询 所有对应的 攻略id
     *
     * @param userId
     * @return
     */
    private void getUserStrategyIds(String userId) {
        final CountDownLatch latch = new CountDownLatch(1); // 初始化CountDownLatch

        new Thread() {
            @Override
            public void run() {
                Request request = new Request();
                String strategyIdsJson = request.get("/strategies/" + userId);
                try {
                    if ("-1".equals(strategyIdsJson)) {
                        Log.w("StrategyListAdapter", "Received unexpected value '-1' instead of a JSON array.");
                        strategyIdList.clear();
                    } else {
                        JSONArray jsonArray = new JSONArray(strategyIdsJson);
                        for (int i = 0; i < jsonArray.length(); i++) {
                            String strategyId = jsonArray.getString(i);
                            strategyIdList.add(strategyId);
                        }
                    }
                } catch (JSONException e) {
                    Log.e("StrategyListAdapter", "Error parsing strategyIds JSON", e);
                } finally {
                    latch.countDown(); // 异步任务结束后，减少计数
                }
            }
        }.start();

        try {
            latch.await(); // 阻塞调用线程，直到countDown()被调用，计数为0
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            Log.e("Error", "Thread interrupted while waiting", e);
        }
    }


    static class ViewHolder {
        TextView strategy_item_tag;
        TextView strategy_item_title;
        TextView strategy_item_content;
        TextView if_user_strategy;
    }

    public interface OnItemClickListener {
        void onItemClick(Map<String, String> map);
    }
}
